package webmote.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.MouseListenerAdapter;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

public class Webmote implements EntryPoint {

    public void onModuleLoad() {
        final ScreenPanel screen = new ScreenPanel();

        RemoteScreenAsync remoteScreen = getRemoteScreen();
        remoteScreen.getSize(new AsyncCallback<ScreenSize>() {
            public void onSuccess(ScreenSize result) {
                screen.setSize(result.getWidth() + "px", result.getHeight() + "px");
            }

            public void onFailure(Throwable caught) {
                GWT.log("RemoteScreen.getSize() failed", caught);
            }
        });

        final AsyncCallback<int[][]> titlesIdsGetterCallback = new AsyncCallback<int[][]>() {
            public void onSuccess(int[][] result) {
                screen.setTilesIds(result);
            }
            
            public void onFailure(Throwable caught) {
                GWT.log("RemoteScreen.getTiles() failed", caught);
            }
        };
		remoteScreen.getTilesIds(titlesIdsGetterCallback);
        
        RootPanel.get().add(screen);

        screen.addMouseListener(new MouseListenerAdapter() {
            @Override
            public void onMouseMove(Widget sender, int x, int y) {
                // TODO: send mouse event
            }

            @Override
            public void onMouseDown(Widget sender, int x, int y) {
                // TODO: send mouse event
            }

            @Override
            public void onMouseUp(Widget sender, int x, int y) {
                // TODO: send mouse event
            }
        });
        
        Timer timer = new Timer() {
            @Override
            public void run() {
                getRemoteScreen().getTilesIds(titlesIdsGetterCallback);
            }
        };
        
        timer.scheduleRepeating(3000);
    }

    private RemoteScreenAsync getRemoteScreen() {
        RemoteScreenAsync remoteScreen = GWT.create(RemoteScreen.class);
        ((ServiceDefTarget) remoteScreen).setServiceEntryPoint(GWT.getModuleBaseURL() + "screen");
        return remoteScreen;
    }

}
